$(document).ready(function(){
    var body = $(document.body),
        resource = [],
        //选择的用户信息
        user = {},
        //选择的分享帖
        shareTie = {},
        // 内部使用，删除文件用
        // resource01 = [],
        //图片序号
        _n=0,
        //是否存在文件上传标志位
        isUploading = false,
        //保存分享帖的源帖类型
        sourceMsgType = '';

        filer_default_opts = {
            changeInput2: "<a class='jFiler-input-choose-btn blue-light' style='margin-bottom: 10px;'>上传文件</a>",
            // changeInput2: '<div class="jFiler-input-dragDrop"><div class="jFiler-input-inner"><div class="jFiler-input-icon"><i class="icon-jfi-cloud-up-o"></i></div><div class="jFiler-input-text"><h3>拖动文件至此</h3> <span style="display:inline-block; margin: 15px 0">or</span></div><a class="jFiler-input-choose-btn blue-light">上传文件</a></div></div>',
            limit: null,
            templates: {
                box: '<ul class="jFiler-items-list jFiler-items-grid"></ul>',
                item: '<li class="jFiler-item" style="width: 25%">\
                            <div class="jFiler-item-container">\
                                <div class="jFiler-item-inner">\
                                    <div class="jFiler-item-thumb">\
                                        <div class="jFiler-item-status"></div>\
                                        <div class="jFiler-item-info">\
                                            <span class="jFiler-item-title"><b title="{{fi-name}}">{{fi-name | limitTo: 25}}</b></span>\
                                            <span class="jFiler-item-others">{{fi-size2}}</span>\
                                        </div>\
                                        {{fi-image}}\
                                    </div>\
                                    <div class="jFiler-item-assets jFiler-row">\
                                        <ul class="list-inline pull-left">\
                                            <li>{{fi-progressBar}}</li>\
                                        </ul>\
                                        <ul class="list-inline pull-right">\
                                            <li><a class="icon-jfi-trash jFiler-item-trash-action"></a></li>\
                                        </ul>\
                                    </div>\
                                </div>\
                            </div>\
                        </li>',
                itemAppend: '<li class="jFiler-item" style="width: 25%">\
                                <div class="jFiler-item-container">\
                                    <div class="jFiler-item-inner">\
                                        <div class="jFiler-item-thumb">\
                                            <div class="jFiler-item-status"></div>\
                                            <div class="jFiler-item-info">\
                                                <span class="jFiler-item-title"><b title="{{fi-name}}">{{fi-name | limitTo: 25}}</b></span>\
                                                <span class="jFiler-item-others">{{fi-size2}}</span>\
                                            </div>\
                                            {{fi-image}}\
                                        </div>\
                                        <div class="jFiler-item-assets jFiler-row">\
                                            <ul class="list-inline pull-left">\
                                                <li><span class="jFiler-item-others">{{fi-icon}}</span></li>\
                                            </ul>\
                                            <ul class="list-inline pull-right">\
                                                <li><a class="icon-jfi-trash jFiler-item-trash-action"></a></li>\
                                            </ul>\
                                        </div>\
                                    </div>\
                                </div>\
                            </li>',
                progressBar: '<div class="bar"></div>',
                itemAppendToEnd: false,
                removeConfirmation: true,
                _selectors: {
                    list: '.jFiler-items-list',
                    item: '.jFiler-item',
                    progressBar: '.bar',
                    remove: '.jFiler-item-trash-action'
                }
            },
            dragDrop: {},
            uploadFile: {
                url: "/common/uploadFiles",
                data: {},
                type: 'POST',
                enctype: 'multipart/form-data',
                beforeSend: function(file){
                    console.log(file);
                    isUploading = true;
                    // for(var i = 0; i < $("#demo-fileInput-6")[0].files.length; i++) {
                    //     if($("#demo-fileInput-6")[0].files[i].type === 'video/mp4') {
                    //         FileValue($("#demo-fileInput-6")[0].files[i]);
                    //     }
                    // }
                },
                success: function(data, el){
                    isUploading = false;
                    var parent = el.find(".jFiler-jProgressBar").parent();
                    var fileData = data.data[0];
                    var obj = {};
                    if (fileData.format === 'png' || fileData.format === 'jpg' || fileData.format === 'gif' || fileData.format === 'bmp') {
                        //判断图片是横向还是纵向 1为横向，2为纵向
                        var mediaDirection = ($(".jFiler-item-thumb-image").eq(_n).find('img').height()/$(".jFiler-item-thumb-image").eq(_n).find('img').width())>1.1 ? 2 : 1;
                        obj = {
                            "createDate": null,
                            "forumMessageId": null,
                            "highQualityImageUrl": null,
                            "imageIndex": _n++,  //图片显示的位置  （具体含义资讯曾立志）
                            "mediaType": "picture",
                            "imageUrl": fileData.url,
                            "mediaResourceId": null,
                            "videoSize": null,
                            "videoTime": null,
                            "videoUrl": null,
                            "songName": null,
                            "singerName": null,
                            "mediaResourceName": null,
                            "songUrl": null,
                            "mediaDirection": mediaDirection
                        };
                        el.find(".jFiler-jProgressBar").fadeOut("slow", function(){
                            $("<div class=\"jFiler-item-others text-success\"><i class=\"icon-jfi-check-circle\"></i> Success</div>").hide().appendTo(parent).fadeIn("slow");
                        });
                        resource.push(obj);
                    } else if(fileData.format === 'mp4' || fileData.format === 'avi' || fileData.format === 'flv' || fileData.format === 'rmvb' || fileData.format === 'mpg'){
                        //获取视频时长以及视频宽高比
                        var id = parseInt(Math.random()*10000);
                        $('body').append("<video src='' id="+ id +" style='display: none'></video>")
                        $("#"+id).prop("src",fileData.url);
                        $("#"+id)[0].addEventListener("loadedmetadata", function() {
                            var tol = this.duration;//获取总时长
                            obj = {
                                "createDate": null,
                                "forumMessageId": null,
                                "highQualityImageUrl": null,
                                "imageIndex": null,
                                "mediaType": "video",
                                "imageUrl": null,
                                "mediaResourceId": null,
                                "videoSize": fileData.size,
                                "videoTime": tol,
                                "videoUrl": fileData.url,
                                "songName": null,
                                "singerName": null,
                                "mediaResourceName": null,
                                "songUrl": null,
                                "mediaDirection": this.videoHeight/this.videoWidth >1.1 ? 2 : 1
                            };
                            resource.push(obj);
                            $("#"+id).remove();
                        });
                        // $("#"+id).remove();
                        // obj = {
                        //     "createDate": null,
                        //     "forumMessageId": null,
                        //     "highQualityImageUrl": null,
                        //     "imageIndex": null,
                        //     "mediaType": "video",
                        //     "imageUrl": null,
                        //     "mediaResourceId": null,
                        //     "videoSize": fileData.size,
                        //     "videoTime": null,
                        //     "videoUrl": fileData.url,
                        //     "songName": null,
                        //     "singerName": null,
                        //     "mediaResourceName": null,
                        //     "songUrl": null,
                        //     "mediaDirection": null
                        // };
                        el.find(".jFiler-jProgressBar").fadeOut("slow", function(){
                            $("<div class=\"jFiler-item-others text-success\"><i class=\"icon-jfi-check-circle\"></i> Success</div>").hide().appendTo(parent).fadeIn("slow");
                        });
                    }
                    // else if(fileData.format === 'mp3' || fileData.format === 'wma' || fileData.format === 'mp4') {
                    //     obj = {
                    //         "createDate": null,
                    //         "forumMessageId": null,
                    //         "highQualityImageUrl": null,
                    //         "imageIndex": null,
                    //         "mediaType": "video",
                    //         "imageUrl": null,
                    //         "mediaResourceId": null,
                    //         "videoSize": null,
                    //         "videoTime": null,
                    //         "videoUrl": null,
                    //         "songName": $(".jFiler-item-title b").html(),
                    //         "singerName": null,
                    //         "mediaResourceName": null,
                    //         "songUrl": fileData.url,
                    //         "mediaDirection": null
                    //     }
                    // }
                    else {
                            alert("上传文件格式仅限于视频和图片，请重新上传！！");
                            el.find(".jFiler-jProgressBar").fadeOut("slow", function(){
                                $("<div class=\"jFiler-item-others text-error\"><i class=\"icon-jfi-minus-circle\"></i> Error</div>").hide().appendTo(parent).fadeIn("slow");
                            });
                    };
                    // resource.push(obj);
                    // obj.fileId = fileData.fileId;
                    // resource01.push(obj);
                },
                error: function(el){
                    var parent = el.find(".jFiler-jProgressBar").parent();
                    el.find(".jFiler-jProgressBar").fadeOut("slow", function(){
                        $("<div class=\"jFiler-item-others text-error\"><i class=\"icon-jfi-minus-circle\"></i> Error</div>").hide().appendTo(parent).fadeIn("slow");    
                    });
                },
                statusCode: null,
                onProgress: null,
                onComplete: null
            },
            onRemove: function(itemEl, file, id, listEl, boxEl, newInputEl, inputEl){
                // var file = file.name;
                // $.post('/common/deleteFile??fileId='+fileId);
            },
        };

    function FileValue(val){
        // var file =val.files[0];
        var url = URL.createObjectURL(val);
        var id = parseInt(Math.random()*10000);
        $(body).append("<video src='' id="+ id +" style='display: none'></video>")
        $("#"+id).prop("src",url);
        $("#"+id)[0].addEventListener("loadedmetadata", function(){
            var tol = this.duration;//获取总时长
            return {
                time: tol,
                percent: this.videoHeight/this.videoWidth
            }
            // console.log(tol);
            // console.log(this.videoWidth);
            // console.log(this.videoHeight);
            // alert("时长："+tol);
            // alert("宽度"+this.videoWidth);
            // alert("高度"+this.videoHeight);
        });
    }
    
    //Run PrettyPrint
    prettyPrint();
    
    //Pre Collapse
    $('.pre-collapse').on("click", function(e){
        var collapse_class = 'collapsed',
            title = ["<i class=\"fa fa-code pull-left\"></i> + Show the source code", "<i class=\"fa fa-code pull-left\"></i> - Hide the source code"],
            $parent = $(this).closest('.pre-box'),
            $pre = $parent.find('pre').first();
        
        if($parent.hasClass(collapse_class)){
            $pre.slideDown("fast", function(){
                $parent.removeClass(collapse_class);
            });
            $(this).html(title[1]);
        }else{
            $pre.slideUp("fast", function(){
                $parent.addClass(collapse_class);
            });
            $(this).html(title[0]);
        }
    });
    $('#demo-fileInput-6').filer({
        changeInput: filer_default_opts.changeInput2,
        showThumbs: true,
        theme: "dragdropbox",
        
        templates: filer_default_opts.templates,
        dragDrop: filer_default_opts.dragDrop,
        uploadFile: filer_default_opts.uploadFile,
        onRemove: filer_default_opts.onRemove
    });


    $("#demo-fileInput-6").prop('name','files');


    //时间选择器插件配置
    Date.prototype.Format = function (fmt) { //author: meizz
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "h+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };
    var time = new Date().Format("yyyy-MM-dd hh:mm:ss");
    $("#day").val(time.split(' ')[0]);
    $("#time").val(time.split(' ')[1]);
    $("#day").click(function () {
        var timer = shareTie.createDate ? shareTie.createDate.split(' ')[0] : '2017-08-08';
        WdatePicker({
            minDate: '2017-08-08',
            onpicked: function () {
                console.log($dp.cal.newdate	)
            }
        })
    });
    $("#time").click(function () {
        WdatePicker({skin:'whyGreen',dateFmt:'H:mm:ss'})
    });

    //调用获取标签方法
    getLable();
    //调用获取分享帖方法
    getNoteList();

    //选择用户列表
    $('.selectUser').on('click',function () {
        getAdminUser();
    });

    // 切换至公开帖
    $("#optionsRadios1").change(function () {
        if ($("#optionsRadios1").prop('checked') === true) {
            $(".share").hide();
            $("#section4").show();
            $(".shareContent").css('display','none');
            $('.mediaList').empty();
            $('body').css('overflow','auto');
            shareTie = []
            $('#demo-fileInput-6').filer({
                changeInput: filer_default_opts.changeInput2,
                showThumbs: true,
                theme: "dragdropbox",
                templates: filer_default_opts.templates,
                dragDrop: filer_default_opts.dragDrop,
                uploadFile: filer_default_opts.uploadFile,
                onRemove: filer_default_opts.onRemove
            });
            $("#demo-fileInput-6").prop('name','files');

            //重新设置时间插件属性
            $(".time").empty();
            $(".time").append("<input class='Wdate' type='text' id='day' /><input class='Wdate' type='text' id='time' />")
            var time = new Date().Format("yyyy-MM-dd hh:mm:ss");
            $("#day").val(time.split(' ')[0]);
            $("#time").val(time.split(' ')[1]);
            $("#day").click(function () {
                WdatePicker({
                    minDate: '2017-08-08',
                    onpicked: function () {
                        console.log($dp.cal.newdate	)
                    }
                })
            });
            $("#time").click(function () {
                WdatePicker({
                    skin:'whyGreen',
                    dateFmt:'H:mm:ss',
                    minDate: '0:00:00'
                })
            });
        }else {
            return
        }
    });

    //切换至分享帖
    $("#optionsRadios2").change(function () {
        if ($("#optionsRadios2").prop('checked') === true) {
            $('html,body').animate({scrollTop:0,scrollLeft:0},100);
            $(".share").show();
            $('body').css('overflow','hidden');
            // $("#section4").html("<div class='container'><div class='row'><div class='col-md-12'><div class='tab-content'><div role='tabpanel' class='tab-pane pt20 pb20 active in' id='demo-dragdrop'><div class='row'><div class='col-md-12' style='width: 100%;'><div class='col-md-12' style='width: 100%;'><input type='file' name='files' id='demo-fileInput-6' multiple></div></div></div></div></div></div></div></div>");
            // $("#section4").html($("#section").clone().html());
            // $('#demo-fileInput-6').filer({
            //     changeInput: filer_default_opts.changeInput2,
            //     showThumbs: true,
            //     theme: "dragdropbox",
            //     templates: filer_default_opts.templates,
            //     dragDrop: filer_default_opts.dragDrop,
            //     uploadFile: filer_default_opts.uploadFile,
            //     onRemove: filer_default_opts.onRemove
            // });
            // $("#demo-fileInput-6").prop('name','files');
            // resource = [];
        }else {
            return;
        }
    });

    // $('.share .cancel').click(function () {
    //     var template = '',
    //            html = '';
    //     for(var i = 0; i < resource.length; i++) {
    //         template = $("#reasource").clone().html();
    //         html = template.replace('reasourceName', '');
    //         html = html.replace('reasourceImg',"<img src="+(info.image_url ? info.image_url : info.imageUrl)+">");
    //         $(".shareContentRight .mediaList").append(html);
    //     }
    //
    // });

    //选中分享帖
    $(".confirmNode").click(function () {
        var tableData = $("#yuanfen_table").bootstrapTable("getSelections")[0];
        console.log(tableData)
        if(tableData == null || tableData.length === 0) {
            alert("请选择帖子");
            return false;
        }
       $(".share").hide();
        $("#section4").html("<div class='container'><div class='row'><div class='col-md-12'><div class='tab-content'><div role='tabpanel' class='tab-pane pt20 pb20 active in' id='demo-dragdrop'><div class='row'><div class='col-md-12' style='width: 100%;'><div class='col-md-12' style='width: 100%;'><input type='file' name='files' id='demo-fileInput-6' multiple></div></div></div></div></div></div></div></div>");
        resource = [];
        $("#section4").hide();
        $(".shareContent").css('display','block');
        $(".shareContentLeft img").attr('src',tableData.userHeadUrl);
        $(".shareContentLeft .shareInfo .name").html(tableData.nickName);
        $(".shareContentLeft .shareInfo .createTime").html(tableData.createDate);
        $(".shareContentRight .text").html(tableData.msgContent);
        //保存分享帖类型
        sourceMsgType = tableData.msgType;
        //将媒体资源渲染到预览modal上
        if (tableData.listForummediaresource != null && tableData.listForummediaresource != []) {
            for(var i = 0; i < tableData.listForummediaresource.length; i++) {
                // $(".shareContentRight .mediaList").append("<li><img src='image/control.png'></li>");
                var template = $("#reasource").clone().html();
                var info = tableData.listForummediaresource[i];
                if (info.mediaType === 'music') {
                    var html = template.replace('reasourceName', info.songName+'-'+info.singerName);
                    html = html.replace('reasourceImg',"<span class='jFiler-icon-file f-audio'><i class='icon-jfi-file-audio'></i></span>");
                    $(".shareContentRight .mediaList").append(html);
                } else if (info.mediaType === 'video') {
                    // var html = template.replace('reasourceName', '');
                    // html = html.replace('reasourceImg',"<span class='jFiler-icon-file f-audio'><i class='icon-jfi-file-video'></i></span>");
                    var html = "<li><div><video style='width: 100%;' controls src="+info.videoUrl+"></video></div></li>";
                    $(".shareContentRight .mediaList").append(html);
                } else {
                    var html = template.replace('reasourceName', '');
                    html = html.replace('reasourceImg',"<img src="+(info.image_url ? info.image_url : info.imageUrl)+">");
                    $(".shareContentRight .mediaList").append(html);
                };
                $(".shareContentRight .mediaList li").css('width','30%');
            };
        };
        $('body').css('overflow','auto');
        shareTie = tableData;
        //重新设置时间插件属性
        $(".time").empty();
        $(".time").append("<input class='Wdate form-control' type='text' id='day' /><input class='Wdate form-control' type='text' id='time' />")
        // $("#day").val(tableData.createDate.split(' ')[0]);
        // $("#time").val(tableData.createDate.split(' ')[1]);
        $("#day").val(new Date().format("yyyy-MM-dd"));
        $("#time").val(new Date().format("hh:mm:ss"));
        $("#day").click(function () {
            WdatePicker({
                minDate: shareTie.createDate,
                onpicked: function () {
                    console.log($dp.cal.newdate	)
                }
            })
        });
        $("#time").click(function () {
            WdatePicker({
                skin:'whyGreen',
                dateFmt:'H:mm:ss'
                // minDate: shareTie.createDate.split(' ')[1]
            })
        });
    });
    $(".cancel").click(function () {
        $(".share").hide();
        $("#optionsRadios2").prop('checked', false);
        $("#optionsRadios1").prop('checked', true);
        $('body').css('overflow','auto');
    });

    //选择用户
    $("#addUserConfirm").click(function () {
        var tableData = $("#user_table").bootstrapTable("getSelections")[0];
        if(tableData && tableData.length != 0) {
            $(".headerUrl img").attr('src', tableData.imageUrl);
            $(".select01 p span").html(tableData.name);
            user =tableData;
            $("#userModal").modal('hide');
        }else {
            alert('请选择用户');
            return false;
        };
    });

    //自定义标签
    // $("#addLabel").change(function () {
    //     if ($("#addLabel").val() === 'customTag') {
    //         $(".customTag").css('display','inline-block');
    //     } else{
    //         $(".customTag").css('display','none');
    //     }
    // });

    //删除文件
    $(document).on('click', '.icon-jfi-trash', function () {
        // console.log(resource01);
        // resource01 = resource;
        console.log($(this).parents('.jFiler-item').index());
        var index = $(this).parents('.jFiler-item').index();
         $.ajax({
             url:  '/common/deleteFile?fileId='+resource[index].fileId,
             type: 'POST',
             cache: false,
             success: function (resb){
                 if (resb.success) {
                     console.log('删除成功');
                 } else {
                     console.log('删除失败');
                 }
             },
             error: function (err) {
                 console.log(err);
             }
         })
        resource.splice(index, 1);
        // resource01.splice(index, 1);
    });

    // 预览帖子
    $("#previewModal").on('show.bs.modal', function() {
        // $(this).find("input[type=text]").val("");
            var el = '';
            if(resource.length > 0) {
                $("#previewModal .resourceContent").css('display', 'block');
                $("#previewModal .shareContent").css('display', 'none');
                el = 'resourceContent';
            } else {
                $("#previewModal .resourceContent").css('display', 'none');
                $("#previewModal .shareContent").css('display', 'block');
                el = 'shareContent';
            };
           var obj = {
               'userHeadUrl': $(".main .headerUrl img").attr('src'),
               'nickName': $('.select01 p span').html(),
               'msgContent': $('.text textarea').val(),
               'listForummediaresource': resource
           };
           console.log(resource);
            updata(obj, shareTie,el);
    });

    //发布帖子
    $(".release").click(function () {
        // if(!isUploading) {
        //     alert("请等待上传完成或者删除上传失败的文件");
        //     return false;
        // }
        if(!user.userId) {
            alert("请选择发帖人！");
            return false;
        };
        var msgContent = $("#addLabel").val() === '' ? $(".text textarea").val() : ("#" + $("#addLabel").find("option:selected").text() + "#" + $(".text textarea").val());
        if(msgContent === '' && resource.length === 0) {
            alert("请勿发布空帖！")
            return false;
        };
        //获取所有资源大小并操作
        var reg = /KB$/gi;
        var reg1 = /MB$/gi;
        var resourceSize  = 0;
        for(var i = 0; i < $('span.jFiler-item-others').length; i++) {
            if(reg.test($('span.jFiler-item-others')[i].innerHTML)) {
                resourceSize += $('span.jFiler-item-others')[i].innerHTML.replace(reg, "")*1;
            }else  if(reg1.test($('span.jFiler-item-others')[i].innerHTML)){
                resourceSize += $('span.jFiler-item-others')[i].innerHTML.replace(reg1, "")*1024;
            }else {
                resourceSize = resourceSize;
            }
        };
        if(resourceSize >= 20480) {
            alert("资源太大，请控制在20MB内");
            return false;
        }
        // add();
        add().done(function(resb){
            console.log(resb);
            if(resb.success) {
                if ($("#select").val() === '0') {
                    alert(resb.message);
                    setTimeout(function () {
                        window.close();
                    }, 1000);
                } else if ($("#select").val() === '2') {
                    $(".headerUrl img").attr('src','image/control.png');
                    $(".select01 p span").html('请选择用户');
                    $(".text textarea").val('');
                    resource = [];
                    user = [];
                    shareTie = [];
                    $(".shareContent").css('display','none');
                    $(".shareContentLeft img").attr('src','');
                    $(".shareContentRight p").html('');
                    $(".shareContentRight .mediaList").empty();
                    $("#section4").show();
                    $("#section4").html("<div class='container'><div class='row'><div class='col-md-12'><div class='tab-content'><div role='tabpanel' class='tab-pane pt20 pb20 active in' id='demo-dragdrop'><div class='row'><div class='col-md-12' style='width: 100%;'><div class='col-md-12' style='width: 100%;'><input type='file' name='files' id='demo-fileInput-6' multiple></div></div></div></div></div></div></div></div>");
                    $('#demo-fileInput-6').filer({
                        changeInput: filer_default_opts.changeInput2,
                        showThumbs: true,
                        theme: "dragdropbox",

                        templates: filer_default_opts.templates,
                        dragDrop: filer_default_opts.dragDrop,
                        uploadFile: filer_default_opts.uploadFile,
                        onRemove: filer_default_opts.onRemove
                    });
                    $("#demo-fileInput-6").prop('name','files');
                    alert(resb.message);
                }else {
                    alert(resb.message);
                    return;
                };
            }else {
                alert(resb.message);
                return false;
            };
        });

    });

    //获取标签
    function getLable() {
        return $.ajax({
            url: '/community/forumMessageLabel/queryAllForumMessageLabel',
            type: 'GET',
            cache: false,
            success: function (resb) {
                console.log(resb);
                if(resb.success) {
                    var data = resb.data;
                    // var arr = [];
                    $('#addLabel').empty().append("<option value=''></option>");
                    if(data.length >0 && data.length){
                        for (var i = 0; i < data.length; i++) {
                            if (data[i].userId === null && data[i].labelStatus === 0) {
                                // $('#addLabel').append("<input type='checkbox' value="+data[i].forumMessageLabelId+" /> &nbsp;&nbsp;<span style='vertical-align: top;'>"+data[i].labelDescribe+"</span> &nbsp;&nbsp;");
                                $('#addLabel').append("<option value="+data[i].forumMessageLabelId+">"+data[i].labelDescribe+"</option>");
                            };
                        };
                    };
                }else{
                    console.log(resb.data);
                };
                // $('#addLabel').append("<option value='customTag'>自定义标签</option>");
            },
            error:function (err) {
                console.log(err);
            }
        });
    };


    //获取系统用户
    function getAdminUser(){
        $("#user_table").bootstrapTable('destroy');
        $("#user_table").bootstrapTable({
            // 'url': '../serviceType/findAll',
            'url': '/user/admin/findUsers?type=2',
            'toolbar': $('div[data-name="btnCtl"]'),
            'queryParams': queryParams,
            'cache':false,
            'sidePagination': 'server',
            'toolbarAlign': 'right',
            'undefinedText': '-',
            'striped': true,
            'pagination': true,
            'sortable': true, //是否启用排序
            'sortOrder': "asc", //排序方式
            // 'pageSize': globalPageSize,
            'pageList': [],
            'clickToSelect': true,
            'singleSelect': true,
            'smartDisplay': true,
            'ajaxOptions':{
                headers: {"Authorization":localStorage.token}
            },
            'responseHandler': function (resb) {
                console.log(resb.data.content);
                return {
                    'total': resb.data.total,
                    'rows': resb.data.content
                }
            },
            'columns': [{
                'checkbox': true
                // 'class': 'hide'
            },
                {
                    'title': '序号',
                    'formatter': function (value, row, index) {
                        return index+1;
                    }
                },
                {
                    'field': 'imageUrl',
                    'title': '用户头像',
                    'align': 'center',
                    'formatter': function (imageUrl) {
                        return "<image src='"+imageUrl+"' style='width: 30px;'>";
                    }
                },{
                    'field': 'name',
                    'title': '昵称',
                    'align': 'center'

                },{
                    'field': 'gender',
                    'title': '性别',
                    'align': 'center',
                    'formatter': function (gender) {
                        var obj = {'0':'女','1':'男'};
                        return obj[gender];
                    }
                },{
                    'field': 'bornDate',
                    'title': '出生日期',
                    'align': 'center'

                },{
                    'field': 'jobName',
                    'title': '行业',
                    'align': 'center'
                }
            ]
        });
    };
//请求服务数据时所传参数
function queryParams(params){
    return {
        type: 2,
        limit : params.limit, //每一页的数据行数，默认是上面设置的10(pageSize)
        offset : params.offset
    }
};

$("#userSearch").click(function () {
    var queryData = {
        'name': $('#userModal .nickName').val() === "" ? null : $('#userModal .nickName').val(),
        'gender': $('#search-gender').val() === "" ? null : $('#search-gender').val(),
        'type': 2,
        limit : 10, //每一页的数据行数，默认是上面设置的10(pageSize)
        offset : 0
    };
    userQuery(queryData);
});

//    查询其他用户
function userQuery(queryData) {
    // if(($("#nickname").val()== '')&&($("#phoneno").val())=='' ){
    // 	$('#user_table').bootstrapTable('refreshOptions',{pageNumber:1,pageSize:globalPageSize});
    // }else{
    $.ajaxSetup({cache:false});
    $.ajax({
        type: "POST",
        url: "/user/admin/findUsers",
        //data: JSON.stringify(queryData),
        data: queryData,
        dataType: 'json',
        //contentType: 'application/json',
        success: function(resb) {
            console.log(resb.data);
            if (resb.data.length != 0) {
                $("#user_table").bootstrapTable('load',  {
                    'total': resb.data.total,
                    'rows': resb.data.content,
                } );
            } else {
                $("#user_table").bootstrapTable('removeAll');
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
    //}
    return false;
};


//   获取帖子列表
    function getNoteList() {
        $("#yuanfen_table").bootstrapTable({
            'method': 'post',
            // 'url': '../serviceType/findAll',
            'url': '/community/forummessage/queryAllForumMsg',
            'toolbar': $('div[data-name="btnCtl"]'),
            'queryParams': query_params,
            'cache':false,
            'sidePagination': 'server',
            'toolbarAlign': 'right',
            'undefinedText': '-',
            'striped': true,
            'pagination': true,
            'sortable': true, //是否启用排序
            'sortOrder': "asc", //排序方式
            'pageSize': 15,
            'pageList': [],
            'clickToSelect': true,
            'singleSelect': true,
            'smartDisplay': true,
            'ajaxOptions':{
                headers: {"Authorization": sessionStorage.token}
            },
            'responseHandler': function (resb) {
                return {
                    'total': resb.data.total,
                    'rows': resb.data.rows
                }
            },
            'onCheck': function() {
                $("button[data-target='#ForumInfoModal'],button[data-target='#commentModal'],button[data-target='#updateModal'], button[data-target='#deleteModal']").removeAttr("disabled");
            },
            'onUncheck': function() {
                $("button[data-target='#ForumInfoModal'],button[data-target='#commentModal'],button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
            },
            'onPageChange': function() {
                if($("#yuanfen_table").bootstrapTable('getSelections')[0]){
                    $("#yuanfen_table").bootstrapTable('uncheckBy', {
                        field: 'typeId',
                        values: [$("#yuanfen_table").bootstrapTable('getSelections')[0].typeId]
                    });
                }

            },
            'columns': [{
                'checkbox': true,
                // 'class': 'hide'
            },
                {
                    'title': '序号',
                    'align': 'center',
                    'formatter': function (value, row, index) {
                        return index+1;
                    }
                }, {
                    'field': 'userId',
                    'title': '用户ID',
                    'align': 'center',
                    'class': 'hide'

                },
                {
                    'field': 'nickName',
                    'title': '用户昵称',
                    'align': 'center'
                },
                {
                    'field': 'allowViewStatus',
                    'title': '权限',
                    'align': 'center',
                    'formatter': function (allowViewStatus) {
                        var obj = {'0':'公开','1':'好友可见','2':'部分好友不可见','3':'部分好友可见','4':'指定群组','5':'仅限自己'};
                        return obj[allowViewStatus];
                    }
                },
                {
                    'field': 'msgType',
                    'title': '帖子类型',
                    'align': 'center',
                    'formatter': function (msgType) {
                        var obj = {'msg':'帖子','shareMsg':'分享的帖子','shareNews':'分享的新闻','shareGroup':'分享的小组','shareVideo':'分享的视频','groupMsg':'小组的帖子'};
                        return obj[msgType];
                    }
                },{
                    'field': 'msgContent',
                    'title': '帖子内容',
                    'width':300,
                    'align': 'center'

                },{
                    'field': 'reportCount',
                    'title': '举报次数',
                    'align': 'center'

                },{
                    'field': 'commentCount',
                    'title': '评论次数',
                    'align': 'center',
                },{
                    'field': 'likesCount',
                    'title': '点赞个数',
                    'align': 'center'

                },{
                    'field': 'msgDelete',
                    'title': '是否删除',
                    'align': 'center'
                },{
                    'field': 'createDate',
                    'title': '发帖时间',
                    'align': 'center',
                    'sortable': true
                }

            ]
        });
    };
    //请求服务数据时所传参数
    function query_params(params){
        return {
            'nickName': $("#search-nickname").val() === "" ? null : $("#search-nickname").val(),
            'startCreateDate': $('#startDate').val() === '' ? null : $('#startDate').val() + ' 00:00:00',
            'endCreateDate': $('#endDate').val() === '' ? null : $('#endDate').val() +  ' 23:59:59',
            'allowViewStatus': 0,
            limit : params.limit, //每一页的数据行数，默认是上面设置的10(pageSize)
            offset : params.offset/params.limit+1 //当前页面,默认是上面设置的1(pageNumber)
        }
    };

    $("#tieZiSearch").on('click',function () {
        yuanfenQuery();
    });

    /**
     * 猿粪查询ajax
     * @param
     */
    function yuanfenQuery() {
        if($("#contentName").val()== ''&&$("#startdate").val()== ''&&$("#enddate").val()== ''&&$(".selectClassify").val()==''){
            $('#yuanfen_table').bootstrapTable('refreshOptions',{pageNumber:1,pageSize:globalPageSize});
        }else{
            var obj = {
                "allowViewStatus": 0,
                // 'msgType': $('#search-msgType').val() === "" ? null : $('#search-msgType').val(),
                // 'maxCommentCount': $('#search-maxCommentCount').val() === "" ? null : $('#search-maxCommentCount').val(),
                // 'minCommentCount': $('#search-minCommentCount').val() === "" ? null : $('#search-minCommentCount').val(),
                // 'maxLikesCount': $('#search-maxLikesCount').val() === "" ? null : $('#search-maxLikesCount').val(),
                // 'minLikesCount': $('#search-minLikesCount').val() === "" ? null : $('#search-minLikesCount').val(),
                // 'maxShareCount': $('#search-maxShareCount').val() === "" ? null : $('#search-maxShareCount').val(),
                // 'minShareCount': $('#search-minShareCount').val() === "" ? null : $('#search-minShareCount').val(),
                'nickName': $("#search-nickname").val() === "" ? null : $("#search-nickname").val(),
                // 'phoneNo': $("#search-phoneNo").val() === "" ? null : $("#search-phoneNo").val(),
                'startCreateDate': $('#startDate').val() === '' ? null : $('#startDate').val() + ' 00:00:00',
                'endCreateDate': $('#endDate').val() === '' ? null : $('#endDate').val() +  ' 23:59:59',
                'limit': 15,
                'offset': 1
            };
            $.ajaxSetup({cache:false});
            $.ajax({
                type: "POST",
                url: "/community/forummessage/queryAllForumMsg",
                data: JSON.stringify(obj),
                contentType: "application/json",
                dataType: 'json',
                // contentType: "application/json",
                beforeSend: function (request) {
                    request.setRequestHeader("Authorization", sessionStorage.token);
                },
                success: function(resb) {
                    console.log(resb);
                    if (resb.data.length != 0) {
                        $("#yuanfen_table").bootstrapTable('load', {
                            'total': resb.data.total,
                            'rows': resb.data.rows
                        });
                    } else {
                        $("#yuanfen_table").bootstrapTable('removeAll');
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus);
                }
            });
        }
        return false;
    }

// });

//    上传帖子
    function add() {
        if(!user.userId) {
            alert("请选择用户！");
            return;
        };
        var imageLayoutType = 0;
        // 根据图片数量和方向确定布局
        // 1为横，2为纵向
        // 一横 (横向)   0
        //  一竖 (方形)   1
        //
        //  2横 (一上一下横向布局)    2
        //  一横一竖 (左右 小方形)    3
        //  两竖 (左右竖立)   4
        //
        //  第一张竖(再1横或2横), 第一张 左边竖向,2,3右边 正方形
        //  第一张横(再1横1竖,或2横)， 第一张上方横向，2、3下方横向长方形
        //  1、3竖 ；2、第一张横，再2竖；左边竖立，宽2/3，2、3右边竖，宽1/3
        //
        //  第一张上方横向,234下方横向  8
        //  第一张左边竖向,234右方竖向 9
        //
        //  五张。上方2 大正方形，下方 3小正方形   10
        //
        //  五张以上100,
        if(resource.length === 1) {
            if(resource[0].mediaDirection === 1) {
                imageLayoutType = 0;
            }else {
                imageLayoutType = 1;
            }
        }else if(resource.length === 2) {
            if(resource[0].mediaDirection === 1) {
                if(resource[1].mediaDirection === 1) {
                    imageLayoutType = 2;
                }else {
                    imageLayoutType = 3;
                }
            }else {
                imageLayoutType = 4;
            }
        }else if(resource.length === 3) {
            if(resource[0].mediaDirection === 2) {
                if(resource[1].mediaDirection === 2 && resource[2].mediaDirection === 2) {
                    imageLayoutType = 7;
                }else {
                    imageLayoutType = 5;
                }
            }else {
                if(resource[1].mediaDirection === 2 && resource[2].mediaDirection === 2) {
                    imageLayoutType = 7;
                }else {
                    imageLayoutType = 5;
                }
            }
        }else if(resource.length === 4) {
            if(resource[0].mediaDirection === 1) {
                imageLayoutType = 8;
            }else {
                imageLayoutType = 9;
            }
        }else if(resource.length === 5) {
            imageLayoutType = 10;
        }else if(resource.length > 5) {
            imageLayoutType = 100;
        }
        var data = {
            "allowViewStatus": 0,
            "firstImageScale": $(".jFiler-item-thumb-image").eq(0).find('img').height() ? ($(".jFiler-item-thumb-image").eq(0).find('img').height()/$(".jFiler-item-thumb-image").eq(0).find('img').width()).toString() :  '0',
            "createDate": $("#day").val() + ' ' + $("#time").val(),
            "imageLayoutType": imageLayoutType,
            "listForummediaresource": resource,
            "listMsgLabelIds": $("#addLabel").val() === 'customTag' ? null : [$('#addLabel').val()],
            "listUserId": null,
            "msgContent":  $("#addLabel").val() === '' ? $(".text textarea").val() : ("#" + $("#addLabel").find("option:selected").text() + "#" + $(".text textarea").val()),
            // "msgStruct": "msg",
            "msgType": sourceMsgType === '' ? 'msg' : 'shareMsg',
            "nickName": user.name,
            "postionLabel": $(".address").html(),
            // "userDefineLabel": $(".customTag").val() ? $(".customTag").val() : null,  //用户自定义标签
            "userHeadUrl": user.imageUrl,  //用户头像url
            "userId": user.userId, //用户id
            "userLatitude": user.longitude, //用户纬度
            "userLongitude": user.latitude, //用户经度
            "userType": "2",  //用户类型
            "sourceId": shareTie.forumMsgId ? shareTie.forumMsgId : null,
            "msgSourceType": sourceMsgType === '' ? null : sourceMsgType
        };
        return $.ajax({
            type: "POST",
            url: '/community/forummessage/publishForumMsg',
            data: JSON.stringify(data),
            contentType: "application/json",
            dataType: 'json',
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", sessionStorage.token);
            },
            success: function() {

            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                // console.log(XMLHttpRequest, textStatus, errorThrown);
                alert(textStatus);
            }
        });
    }

//    预览帖子
    function updata(data, share, el) {
        console.log(el);
        console.log(share);
        if(el === 'shareContent') {
            $("#previewModal .shareContent .img img").attr('src', share.userHeadUrl);
            $("#previewModal .shareContent .shareUser .shareUserName").html(share.nickName);
            $("#previewModal .shareContent .shareUser .shareTime").html(share.createDate);
            $("#previewModal .shareContent .shareUser .shareAddress").html(share.postionLabel);
            $("#previewModal .shareContent .shareText").html(share.msgContent);
        }
        $("#previewModal .headerImg img").attr('src', data.userHeadUrl);
        $("#previewModal .info .name").html(data.nickName);
        $("#previewModal .info .address").html($(".main .select02 .address").html());
        // $("#previewModal .info .address").html(user.province);
        $("#previewModal .txtContent p").html(data.msgContent);
        $("#previewModal ."+el+" ul").empty();
        var resourceList = data.listForummediaresource.length > 0 ? data.listForummediaresource : share.listForummediaresource;
        if(resourceList) {
            for (var i = 0; i < resourceList.length; i++) {
                var template = $("#reasource").clone().html();
                var info = resourceList[i];
                if (info.mediaType === 'music') {
                    var html = template.replace('reasourceName', info.songName+'-'+info.singerName);
                    html = html.replace('reasourceImg',"<span class='jFiler-icon-file f-audio'><i class='icon-jfi-file-audio'></i></span>");
                    $("#previewModal ."+el+" ul").append(html);
                } else if (info.mediaType === 'video' || info.mediaType === 'threeDimensionalVideo' || info.mediaType === 'shortVideo') {
                    // var html = template.replace('reasourceName', '');
                    // html = html.replace('reasourceImg',"<span class='jFiler-icon-file f-audio'><i class='icon-jfi-file-video'></i></span>");
                    var html = "<li><div><video style='width: 100%;' controls src="+info.videoUrl+"></video></div></li>";
                    $("#previewModal ."+el+" ul").append(html);
                } else {
                    var html = template.replace('reasourceName', '');
                    html = html.replace('reasourceImg',"<img src="+(info.image_url ? info.image_url : info.imageUrl)+">");
                    $("#previewModal ."+el+" ul").append(html);
                }
            }
        }else{
            $("#previewModal .shareContent").css('display', 'none');
        }
    }
});


/*
 日期格式化
 */
Date.prototype.format = function(fmt) {
    var o = {
        "M+" : this.getMonth()+1,                 //月份
        "d+" : this.getDate(),                    //日
        "h+" : this.getHours(),                   //小时
        "m+" : this.getMinutes(),                 //分
        "s+" : this.getSeconds(),                 //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S"  : this.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt)) {
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
    for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
    return fmt;
}
